package com.halden.TRPG.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.halden.TRPG.common.CodeEnum;
import com.halden.TRPG.common.MyException;
import com.halden.TRPG.entity.RoomKpEntity;
import com.halden.TRPG.mapper.RoomKpMapper;
import com.halden.TRPG.service.RoomKpService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = MyException.class)
public class RoomKpServiceImpl extends ServiceImpl<RoomKpMapper, RoomKpEntity> implements RoomKpService {
    @Override
    public boolean initKp(Long rid, String ownerUid) {
        if (baseMapper.selectOne(new QueryWrapper<RoomKpEntity>().eq("rid",rid)) != null){
            return false;
        }
        RoomKpEntity entity = new RoomKpEntity();
        entity.setRid(rid);
        entity.setKp(ownerUid);
        entity.setOwnerUid(ownerUid);
        int insert = baseMapper.insert(entity);
        return insert == 1;
    }

    @Override
    public CodeEnum setKp(Long rid, String kpUid) {
        RoomKpEntity entity = baseMapper.selectOne(new QueryWrapper<RoomKpEntity>().eq("rid", rid));
        entity.setKp(kpUid);
        int update = baseMapper.updateById(entity);
        if (update == 1){
            return CodeEnum.SUCCESS;
        } else {
            throw new MyException(CodeEnum.OPTION_FAIL_EXCEPTION);
        }
    }

    @Override
    public CodeEnum getKp(Long rid) {
        RoomKpEntity entity = baseMapper.selectOne(new QueryWrapper<RoomKpEntity>().eq("rid", rid));
        if (entity == null){
            throw new MyException(CodeEnum.OPTION_FAIL_EXCEPTION);
        } else {
            return CodeEnum.SUCCESS.setData(entity);
        }
    }

    @Override
    public boolean delete(Long rid) {
        int delete = baseMapper.delete(new QueryWrapper<RoomKpEntity>().eq("rid", rid));
        return delete > 0;
    }
}
